"""
 Django调用序列化器
 Django只支持GET和POST
 获取数据: request.POST
"""
from django.http import JsonResponse
from django.views.decorators.csrf import csrf_exempt

from .models import News, Category
from .serializers import NewsSerializer, CategorySerializer, NewsGetSerializer, CategoryGetSerializer


def getNews(request):
    queryset = News.objects.select_related('category')
    serializer = NewsGetSerializer(instance=queryset, many=True)
    return JsonResponse(serializer.data, safe=False)

@csrf_exempt
def insertNews(request):
    serializer = NewsSerializer(data=request.POST)
    # 有异常抛出
    serializer.is_valid(raise_exception=True)
    serializer.save()
    return JsonResponse(serializer.data, safe=False)

@csrf_exempt
def updateNews(request,pk):
    instance = News.objects.get(pk=pk)
    serializer = NewsSerializer(instance=instance,data=request.POST)
    # 有异常抛出
    serializer.is_valid(raise_exception=True)
    serializer.save()
    return JsonResponse(serializer.data, safe=False)

def delNews(request,pk):
    queryset=News.objects.filter(pk=pk)
    if queryset.exists():
        queryset.first().delete()
        return JsonResponse({'code': 200, 'msg': '删除成功'}, safe=True)
    return JsonResponse({'code': 200, 'msg': '删除失败'}, safe=True)

def getCategorys(request):
    queryset = Category.objects.prefetch_related('news')
    serializer = CategoryGetSerializer(instance=queryset, many=True)
    return JsonResponse(serializer.data, safe=False)